/*
 * Copyright (c) 2009, Hamish Morgan. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the University of Sussex nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package piccat.lib;

import java.util.Arrays;
import java.util.Iterator;

/**
 *
 * @param <E>
 * @author Hamish Morgan
 */
public class Grid<E> implements Iterable<E> {

    private final int rows;
    private final int cols;
    private final Object[][] data;

    public Grid(int rows, int cols) {
        if (rows <= 0 || cols <= 0)
            throw new IllegalArgumentException(
                    "Dimensions must be possitive integers but found: rows = " +
                    rows + ", cols = " + cols);
        this.rows = rows;
        this.cols = cols;
        data = new Object[rows][cols];
    }

    public int getRows() {
        return rows;
    }

    public int getCols() {
        return cols;
    }

    @SuppressWarnings("unchecked")
    public E get(int row, int col) {
        checkBounds(row, col);
        return (E) data[row][col];
    }

    public E get(Index index) {
        return get(index.row, index.col);
    }

    private void checkBounds(int row, int col) {
        if (row < 0 || col < 0 || row >= rows || col >= cols)
            throw new IndexOutOfBoundsException("Index " + row + ", " + col +
                    " is outside the bounds of this grid which has dimensions rows = " +
                    rows + " cols = " + cols);
    }

    public void set(int row, int col, E value) {
        checkBounds(row, col);
        data[row][col] = value;
    }

    public void set(Index index, E value) {
        set(index.row, index.col, value);
    }

    public Index indexOf(E value) {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                E c = get(i, j);
                if (c != null && c.equals(value))
                    return new Index(i, j);
            }
        }
        return null;
    }

    public boolean contains(E value) {
        return indexOf(value) != null;
    }

    public void fill(E value) {
        for (Object[] row : data)
            Arrays.fill(row, value);
    }

    public GridIterator<E> iterator() {
        return new GridIterator<E>(this);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        @SuppressWarnings("unchecked")
        final Grid<E> other = (Grid<E>) obj;
        if (!Arrays.deepEquals(this.data, other.data)) return false;
        return true;
    }

    @Override
    public int hashCode() {
        return Arrays.deepHashCode(this.data);
    }

    @Override
    public String toString() {
        return Arrays.deepToString(data);
    }

    public static class GridIterator<F> implements Iterator<F> {

        private final Grid<F> outer;
        private Index next;
        private Index prev;
        private Index last;

        public GridIterator(Grid<F> outer) {
            this.outer = outer;
            next = new Index(0, 0);
            prev = new Index(-1, -1);            
        }

        public boolean hasNext() {
            return next.row < outer.getRows() && next.col < outer.getCols();
        }

        public boolean hasPrevious() {
            return prev.row >= 0 && prev.col >= 0;
        }

        public F next() {
            final F result = outer.get(next);
            prev.set(next);
            last = prev;
            if (next.col == outer.getCols() - 1) {
                next.col = 0;
                next.row++;
            } else {
                next.col++;
            }
            return result;
        }

        public F previous() {
            final F result = outer.get(prev);
            next.set(prev);
            last = next;
            if (prev.col == 0) {
                prev.col = outer.getCols() - 1;
                prev.row--;
            } else {
                prev.col--;
            }
            return result;
        }

        public Index previousIndex() {
            return prev.clone();
        }

        public Index nextIndex() {
            return next.clone();
        }

        public void set(F value) {
            outer.set(last, value);
        }

        public void remove() {
            throw new UnsupportedOperationException(
                    "Grid has emutable dimensions so items cannot be removed.");
        }
    }
}
